package com.life.xxx.config;

import com.life.xxx.exception.BusinessException;
import com.life.xxx.util.Result;
import com.life.xxx.util.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 * 捕获未处理的异常，统一返回 Result 格式
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理所有未捕获的 Exception
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e, HttpServletRequest request) {
        log.error("【系统异常】 URI: {}, Method: {}, Message: {}",
                request.getRequestURI(), request.getMethod(), e.getMessage(), e);
        return Result.error(ResultCode.ERROR.getCode(), "系统繁忙，请稍后重试");
    }

    /**
     * 处理参数校验异常（可结合 @Valid 使用）
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handleIllegalArgumentException(IllegalArgumentException e) {
        log.warn("【非法参数】{}", e.getMessage());
        return Result.error(ResultCode.INVALID_PARAM.getCode(), e.getMessage());
    }

    /**
     * 处理空指针异常（建议开发阶段避免，生产中兜底）
     */
    @ExceptionHandler(NullPointerException.class)
    public Result handleNullPointerException(NullPointerException e) {
        log.error("【空指针异常】", e);
        return Result.error("10000", "数据异常，请检查输入");
    }

    /**
     * 处理数组越界等运行时异常
     */
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public Result handleIndexOutOfBoundsException(IndexOutOfBoundsException e) {
        log.error("【数组越界】", e);
        return Result.error("10001", "数据索引越界");
    }

    /**
     * 处理 404 - 路由未找到
     * 注意：需要在 application.yml 中开启：
     *   spring:
     *     mvc:
     *       throw-exception-if-no-handler-found: true
     *     web:
     *       resources:
     *         add-mappings: false
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handle404(NoHandlerFoundException e) {
        log.warn("【请求路径不存在】{}", e.getRequestURL());
        return Result.error(ResultCode.ERROR.getCode(), "请求地址不存在");
    }

    /**
     * 处理权限不足（403）
     */
    @ExceptionHandler(SecurityException.class)
    public Result handleSecurityException(SecurityException e) {
        log.warn("【权限异常】{}", e.getMessage());
        return Result.fail(ResultCode.FORBIDDEN);
    }

    /**
     * 自定义业务异常（推荐使用）
     */
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException e) {
        log.warn("【业务异常】{}", e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }
}